<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;

class IndexController extends HomeController {

    public function _initialize(){
        parent::_initialize();
    }

    //首页
    public function index(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $ImageModel = D("Image");
        $ProblemModel = D("Problem");
        $data = [];
        $image_params = [
            'status' => 1
        ];
        $image_result = $ImageModel->get_image_list($image_params,"image");
        if($image_result['list']){
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            foreach($image_result['list'] as $key=>$val){
                $data['image_list'][] = $protocol.$this->img_url.$val['image'];        //图片
            }
        }
        //获取问题
        $problem_params = [
            'status'   => 1,
            'pageSize' => 100,
            'order'    => 'a.sort asc'
        ];
        $problem_field = "a.answer_options,a.type,a.status,a.problem_name,a.id as problem_id,a.is_menu";
        $problem_result = $ProblemModel->get_problem_list($problem_params,$problem_field);
        if($problem_result['list']) {
            foreach ($problem_result['list'] as $key => $val) {
                $val['answer_options'] = json_decode($val['answer_options'],true);
                $data['problem_list'][$key] = $val;
            }
        }
        $returnData = [
            'code' => 200,
            'data' => $data
        ];
        echo json_encode($returnData);
    }




    //获取小程序openid
    public function get_applet_openid($code){
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->APPLET_APPID}&secret={$this->APPLET_SECRET}&js_code={$code}&grant_type=authorization_code";
        $data = ['code'=>$code];
        $result = json_decode($this->httpRequest($url,$data,'POST'),true);
        return $result['openid'];
    }


    //问题提交
    public function problem_save(){
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $model = D("Menu");
        $ChannelRecommendModel = D("ChannelRecommend");
        $ProblemAnswerModel = D("ProblemAnswer");
        if(empty($paramData['problem_list'])) $this->throw_exception('问题信息不能为空');

        $problem_price = $problem_broadband = $problem_internet_traffic = 0;
        foreach($paramData['problem_list'] as $key=>$val){
            if($val['is_menu'] && $val['content']){
                if(empty(is_numeric($val['content'])))  $this->throw_exception("问题:".$val['problem_name']."只能填整数数字");
                $val['is_menu'] == 1?$problem_price += $val['content']:"";      //
                $val['is_menu'] == 3?$problem_broadband += $val['content']:"";
                $val['is_menu'] == 2?$problem_internet_traffic += $val['content']:"";
            }
            $answer_json[] = [
                'problem_id' => $val['problem_id'],
                'content'    => $val['content']
            ];
        }

        $params = [
            'status'    => 1,
            'pageSize'  => 1000,
            'order'     => 'a.price asc'
        ];
        $result = $model->get_menu_list($params);
        $menu_info = [];
        if($result['list']){
            $min_price = $result['list'][0]['price'];
            $count = count($result['list']);
            $max_price = $count > 1?$result['list'][$count-1]['price']:$min_price;
            if($min_price >= $problem_price){
                $menu_info = $result['list'][0];
            }else if($problem_price >= $max_price){
                $menu_info = $result['list'][$count-1];
            }else{
                foreach($result['list'] as $key=>$val){
                    if($val['price'] >= $problem_price && $key != 0){
                        if($val['price'] == $problem_price) $menu_info = $val;
                        if($val['price'] > $problem_price) $menu_info = $result['list'][$key-1];
                        break;
                    }
                }
            }
        }


        if($menu_info['image']){
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $menu_info['image'] = $protocol.$_SERVER['HTTP_HOST'].$menu_info['image'];        //图片
        }
        $menu_info['problem_price']            = number_format($problem_price, 2, '.', '');
        $menu_info['problem_broadband']        = $problem_broadband;
        $menu_info['problem_internet_traffic'] = $problem_internet_traffic;
        $menu_info['price_contrast'] = $menu_info['price'] < $problem_price?"价格更低!":"";
        $menu_info['broadband_contrast'] = $menu_info['broadband'] > $problem_broadband?"速率更高!":"";
        $menu_info['internet_traffic_contrast'] = $menu_info['internet_traffic'] > $problem_internet_traffic?"流量更多!":"";
        $menu_info['content_contrast'] = "";    //套餐内容对比
        $menu_info['summarize'] = "";
        if($menu_info['price'] < $problem_price){
            $money = $problem_price - $menu_info['price'];
            $year_money = $problem_price*12 - $menu_info['price']*12;
            $menu_info['summarize'] = "每月节省{$money}元，一年总共节省{$year_money}元";
        }
        $menu_info['problem_price']            = $menu_info['problem_price']?$menu_info['problem_price']:'0';
        $menu_info['problem_broadband']        = $menu_info['problem_broadband']?$menu_info['problem_broadband']:'0';
        $menu_info['problem_internet_traffic'] = $menu_info['problem_internet_traffic']?$menu_info['problem_internet_traffic']:'0';
        $openid = $this->get_applet_openid($paramData['js_code']);
        if($openid) {
            //添加渠道推荐信息
            $ChannelRecommendModel->channel_recommend_save($openid, $paramData['channel_id']);
            //添加答案信息
            $data = [
                'channel_id'  => $paramData['channel_id'],
                'openid'      => $openid,
                'answer_json' => json_encode($answer_json),
                'create_date' => date('Y-m-d'),
                'create_time' => time()
            ];
            $ProblemAnswerModel->add($data);
        }
        $returnData = ['code' => 200,'data' => $menu_info];
        echo json_encode($returnData);
    }



}